<template>
  <div class="index-page">
    <!-- 搜索框模块 -->
    <el-card>
      <el-row>
        <el-col :span="24">
          <el-form :model="form" label-width="100px" v-show="showSearch">
            <el-row :gutter="20">
              <el-col :span="5">
                <el-form-item label="指标类型" id="index">
                  <el-select
                    clearable
                    v-model="form.indexType"
                    placeholder="请选择指标类型"
                  >
                    <el-option
                      v-for="item in index_type"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="5">
                <el-form-item label="指标名称">
                  <el-input
                    placeholder="请输入指标名称"
                    clearable
                    v-model="form.indexName"
                  >
                  </el-input>
                </el-form-item>
              </el-col>

              <el-col :span="14">
                <el-button type="primary" icon="Search" @click="handleQuery"
                  >搜索</el-button
                >
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              </el-col>
            </el-row>
          </el-form>
        </el-col>
      </el-row>

      <el-row style="margin-bottom: 10px">
        <el-col :span="5">
          <el-button plain type="primary" icon="Plus" @click="handleAdd"
            >新增</el-button
          >
        </el-col>

        <right-toolbar
          v-model:showSearch="showSearch"
          @queryTable="getList"
        ></right-toolbar>
      </el-row>

      <el-table
        v-loading="loading"
        max-height="600"
        height="440"
        :data="tableData"
        stripe
        border
        :cell-style="{ 'text-align': 'center' }"
        :header-cell-style="{ 'text-align': 'center' }"
        style="width: 100%"
      >
        <!-- <el-table-column type="selection" width="55"></el-table-column> -->
        <el-table-column prop="indexType" width="200" label="指标类型">
          <template v-slot:default="scope">
            <!-- {{ undefined }}undefined不显示在模块上 -->
            <span>{{ handleIndexType(scope.row.indexType) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="indexName"
          width="200"
          label="指标名称"
        ></el-table-column>
        <el-table-column prop="indexId" label="指标标识"></el-table-column>
        <el-table-column prop="indexUnit" label="指标单位">
          <template v-slot:default="scope">
            <span>{{ handleIndexUnit(scope.row.indexUnit) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="numericalType"
          label="数值类型"
        ></el-table-column>
        <el-table-column
          prop="numericalPrecision"
          label="数据精度"
        ></el-table-column>
        <el-table-column
          prop="thresholdLowerLimit"
          label="阈值下限"
        ></el-table-column>
        <el-table-column
          prop="thresholdUpperLimit"
          label="阈值上限"
        ></el-table-column>
        <el-table-column label="操作">
          <template v-slot:default="scope">
            <el-button
              icon="Edit"
              type="primary"
              link
              @click="handleEdit(scope.row)"
              >修改</el-button
            >
            <el-button
              icon="Delete"
              type="danger"
              link
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 全局分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="paginationData.page"
        v-model:limit="paginationData.limit"
        @pagination="getList"
      ></pagination>
    </el-card>

    <!-- 新增编辑弹框 -->
    <el-dialog
      width="50%"
      v-model="dialogShow"
      v-if="dialogShow"
      :title="dialogTitle + '指标'"
      :before-close="closeDialog"
      :close-on-click-modal="false"
    >
      <el-form
        ref="ruleFormRef"
        :model="newForm"
        label-width="120px"
        :rules="rules"
      >
        <el-form-item label="指标类型" prop="indexType">
          <el-select
            v-model="newForm.indexType"
            placeholder="请选择指标类型"
            style="width: 100%"
            @change="indexTypeChange"
          >
            <el-option
              v-for="item in index_type"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="指标名称" prop="indexName">
          <el-input
            v-model="newForm.indexName"
            placeholder="请输入指标名称"
          ></el-input>
        </el-form-item>

        <el-form-item label="指标标识" prop="indexId">
          <el-input
            v-model="newForm.indexId"
            placeholder="请输入指标标识"
          ></el-input>
        </el-form-item>

        <el-form-item label="指标单位" prop="indexUnit">
          <el-select
            v-model="newForm.indexUnit"
            placeholder="请选择指标单位"
            style="width: 100%"
            @change="indexUnitChange"
          >
            <el-option
              v-for="item in index_unit"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="数值类型" prop="numericalType">
          <el-input
            v-model="newForm.numericalType"
            placeholder="请输入数值类型"
          ></el-input>
        </el-form-item>

        <el-form-item label="数据精度" prop="numericalPrecision">
          <el-input
            v-model="newForm.numericalPrecision"
            placeholder="请输入数据精度"
            @input="handleInput"
          ></el-input>
        </el-form-item>

        <el-form-item label="阈值下限" prop="thresholdLowerLimit">
          <el-input
            v-model="newForm.thresholdLowerLimit"
            placeholder="请输入阈值下限"
            @input="handleThresholdLowerLimit"
          ></el-input>
        </el-form-item>

        <el-form-item label="阈值上限" prop="thresholdUpperLimit">
          <el-input
            v-model="newForm.thresholdUpperLimit"
            @input="handleThresholdUpperLimit"
            placeholder="请输入阈值上限"
          ></el-input>
        </el-form-item>

        <el-form-item label="备注" prop="notes">
          <el-input
            v-model="newForm.notes"
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 6 }"
            placeholder="请输入备注"
          ></el-input>
        </el-form-item>

        <el-form-item label="指标图片" style="font-weight: 700" prop="iconUrl">
          <el-upload
            class="avatar-uploader"
            :action="url"
            :headers="upload.headers"
            :show-file-list="false"
            :on-success="handleAvatarSuccessRegister"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="RegisterUrl"
              :src="RegisterUrl"
              class="avatar"
              style="width: 280px; height: 180px"
              fit="cover"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>

      <template v-slot:footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="submit(ruleFormRef)"
            >确定</el-button
          >
          <el-button @click="closeDialog">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  getIndexData,
  addNewData,
  editData,
  deleteData,
} from "../../../api/IndexManagement/index.js";
import { ref, reactive, onMounted } from "vue";
import { getToken } from "@/utils/auth";
import { ElMessage, ElMessageBox } from "element-plus";

const { proxy } = getCurrentInstance();
// 字典-指标类型
const { index_type } = proxy.useDict("index_type");

// 字典-指标单位
const { index_unit } = proxy.useDict("index_unit");
console.log(index_unit, "<<<===index_unit-指标单位-数组");

// form表单拿到原生dom
const ruleFormRef = ref();
const RegisterUrl = ref("");
console.log(ruleFormRef, "<<<=== ruleFormRef");
const url = ref(
  process.env.VUE_APP_BASE_API + "/file/upload/pk-home-bed-apply"
);
const upload = reactive({
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
});

// 校验规则
const rules = ref({
  indexType: [
    {
      required: true,
      message: "指标类型不能为空",
      trigger: "change",
    },
  ],
  indexName: [
    {
      required: true,
      message: "指标名称不能为空",
      trigger: "blur",
    },
    { min: 0, max: 10, message: "指标名称长度不能超过10", trigger: "blur" },
  ],
  indexId: [
    {
      required: true,
      message: "指标标识不能为空",
      trigger: "blur",
    },
    { min: 0, max: 15, message: "指标标识长度不能超过15", trigger: "blur" },
  ],
  indexUnit: [
    {
      required: true,
      message: "指标单位不能为空",
      trigger: "change",
    },
  ],
  numericalType: [
    {
      required: true,
      message: "数值类型不能为空",
      trigger: "blur",
    },
  ],
  numericalPrecision: [
    {
      required: true,
      message: "数据精度不能为空",
      trigger: "blur",
    },
    { min: 0, max: 5, message: "数据精度过长", trigger: "blur" },
  ],
  thresholdLowerLimit: [
    {
      required: false,
      min: 0,
      max: 5,
      message: "阈值下限过长",
      trigger: "blur",
    },
  ],
  thresholdUpperLimit: [
    {
      required: false,
      min: 0,
      max: 5,
      message: "阈值上限过长",
      trigger: "blur",
    },
  ],
  notes: [
    {
      required: false,
      min: 0,
      max: 500,
      message: "备注过长",
      trigger: "blur",
    },
  ],
  iconUrl: [
    {
      required: true,
      message: "指标图片不能为空",
      trigger: "blur",
    },
  ],
});

// 弹框表单form数据
const newForm = ref({
  indexType: "",
  indexName: "",
  indexId: "",
  indexUnit: "",
  numericalType: "",
  numericalPrecision: "",
  thresholdLowerLimit: "",
  thresholdUpperLimit: "",
  notes: "",
  iconUrl: "",
});

function handleAvatarSuccessRegister(file) {
  RegisterUrl.value = file.data.url;
  newForm.value.iconUrl = file.data.url;
}
function beforeAvatarUpload(file, fileFist) {
  // 校验图片格式是否合法
  const isLegal =
    file.type === "image/jpeg" ||
    file.type === "image/jpg" ||
    file.type === "image/png";
  // 文件大小不超过2MB
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isLegal) {
    // 文件格式是否合法
    proxy.$modal.msgError("上传头像图片只能是 JPG、JPEG、PNG 格式!");
  }

  if (!isLt2M) {
    // 图片大小超过2MB
    proxy.$modal.msgSuccess("上传头像图片大小不能超过 2MB!");
  }

  return isLegal && isLt2M;
}
// 编辑要用的id
const editId = ref("");

// 显示弹框
const dialogShow = ref(false);
// 弹框标题
const dialogTitle = ref("新增");

const showSearch = ref(true);
const loading = ref(true);
// 搜索表单
const form = reactive({
  indexType: "",
  indexName: "",
});
// 分页
const total = ref(0);
const paginationData = reactive({
  page: 1,
  limit: 10,
});

// 表格
const tableData = ref([]);

// 拿表格数据
const getList = () => {
  loading.value = true;
  // 整理查询参数
  const queryData = {
    page: paginationData.page,
    limit: paginationData.limit,
    indexType: form.indexType,
    indexName: form.indexName,
  };
  getIndexData(queryData)
    .then((res) => {
      console.log(res, "res-查询");
      tableData.value = res.page.list;
      loading.value = false;
      total.value = res.page.totalCount;
      // paginationData.currPage
      // paginationData.pageSize
    })
    .catch((error) => {
      console.log(error, "error");
    });
};

// 点击搜索按钮
const handleQuery = () => {
  getList();
};

// 点击重置按钮
const resetQuery = () => {
  form.indexType = "";
  form.indexName = "";
  getList();
};

// 点击新增按钮
const handleAdd = () => {
  dialogShow.value = true;
  dialogTitle.value = "新增";
};

// 关闭弹框
const closeDialog = () => {
  dialogShow.value = false;
  dialogTitle.value = "";
  // 清空表单的数据
  newForm.value.indexType = "";
  newForm.value.indexName = "";
  newForm.value.indexId = "";
  newForm.value.indexUnit = "";
  newForm.value.numericalType = "";
  newForm.value.numericalPrecision = "";
  newForm.value.thresholdLowerLimit = "";
  newForm.value.thresholdUpperLimit = "";
  newForm.value.notes = "";
  newForm.value.iconUrl = "";
  RegisterUrl.value = "";
};

// 监听指标类型选中时
const indexTypeChange = (e) => {};

// 监听指标单位选中时
const indexUnitChange = (e) => {
  console.log(e, "<<<=== e 指标单位选中");
  console.log(typeof e === "string");
};

// 点击弹框的确定按钮
const submit = (ruleFormRefInstance) => {
  if (!ruleFormRefInstance) return;
  if (newForm.value.thresholdLowerLimit && newForm.value.thresholdUpperLimit) {
    if (newForm.value.thresholdLowerLimit < newForm.value.thresholdUpperLimit) {
      proxy.$modal.msgError("阈值上限不能低于阈值下限");
      return false;
    }
  }
  if (dialogTitle.value === "编辑") {
    // 组装参数
    const editParams = {
      id: editId.value,
      indexType: newForm.value.indexType,
      indexName: newForm.value.indexName,
      indexId: newForm.value.indexId,
      indexUnit: newForm.value.indexUnit,
      numericalType: newForm.value.numericalType,
      numericalPrecision: newForm.value.numericalPrecision,
      thresholdLowerLimit: newForm.value.thresholdLowerLimit,
      thresholdUpperLimit: newForm.value.thresholdUpperLimit,
      notes: newForm.value.notes,
      iconUrl: newForm.value.iconUrl,
    };
    console.log(editParams, "<<<=== editParams");

    ruleFormRefInstance.validate((valid) => {
      console.log(valid, "valid-结果");
      if (valid) {
        editData(editParams)
          .then((res) => {
            console.log(res, "<<<=== res");
            // 关闭弹框
            closeDialog();
            getList();
          })
          .catch((error) => {
            console.log(error, "<<<=== error");
          });
      } else {
        return false;
      }
    });

    return;
  }
  // 下面是新增---------------------------------------------
  ruleFormRefInstance.validate((valid) => {
    if (valid) {
      // 组装参数
      const params = {
        indexType: newForm.value.indexType,
        indexName: newForm.value.indexName,
        indexId: newForm.value.indexId,
        indexUnit: newForm.value.indexUnit,
        numericalType: newForm.value.numericalType,
        numericalPrecision: newForm.value.numericalPrecision,
        thresholdLowerLimit: newForm.value.thresholdLowerLimit,
        thresholdUpperLimit: newForm.value.thresholdUpperLimit,
        notes: newForm.value.notes,
        iconUrl: newForm.value.iconUrl,
      };

      console.log(params, "<<<=== params");

      addNewData(params)
        .then((res) => {
          console.log(res, "<<<=== res 新增");
          // 关闭弹框
          closeDialog();
          getList();
        })
        .catch((error) => {
          console.log(error, "<<<=== error");
        });
    } else {
      return false;
    }
  });
};
function handleInput(event) {
  newForm.value.numericalPrecision = event.replace(/[^0-9.]/g, "");
}
function handleThresholdLowerLimit() {
  newForm.value.thresholdLowerLimit = newForm.value.thresholdLowerLimit.replace(
    /[^0-9.]/g,
    ""
  );
}
function handleThresholdUpperLimit() {
  newForm.value.thresholdUpperLimit = newForm.value.thresholdUpperLimit.replace(
    /[^0-9.]/g,
    ""
  );
}
// 点击修改
const handleEdit = (data) => {
  dialogShow.value = true;
  dialogTitle.value = "编辑";

  console.log(data, "<<<=== data 当前这个行的数据");
  // 保存id,编辑提交要用
  editId.value = data.id;
  console.log(editId.value, "<<<=== editId.value");
  // 数据回显
  newForm.value.indexType = data.indexType;
  newForm.value.indexUnit = data.indexUnit;

  newForm.value.indexName = data.indexName;
  newForm.value.indexId = data.indexId;
  newForm.value.numericalType = data.numericalType;
  newForm.value.numericalPrecision = data.numericalPrecision;
  newForm.value.thresholdLowerLimit = data.thresholdLowerLimit;
  newForm.value.thresholdUpperLimit = data.thresholdUpperLimit;
  newForm.value.notes = data.notes;
  newForm.value.iconUrl = data.iconUrl;
  RegisterUrl.value = data.iconUrl;
};

// 点击删除
const handleDelete = (data) => {
  console.log(data, "<<<=== 点击删除-data");
  ElMessageBox.confirm(`是否确定删除${data.indexName}`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deleteData([data.id])
        .then((res) => {
          console.log(res, "<<<=== res");
          getList();
          ElMessage({
            type: "success",
            message: "删除成功",
          });
        })
        .catch((error) => {
          console.log(error, "<<<=== error");
        });
    })
    .catch((error) => {
      console.log(error, "error");
      ElMessage({
        type: "warning",
        message: "取消删除",
      });
    });
};

// 写方法处理指标单位的显示-目前后端返回的的数据有问题，次方法会报错，等后端修改数据就好了
const handleIndexUnit = (data) => {
  // console.log(index_unit, "<<<=== index_unit333");
  return index_unit.value.find((item) => {
    return item.value === data;
  })?.label;
};

// 写方法处理指标类型的显示-注意：如果这个函数最后返回的是undefined,undefined在模板上是不显示的
const handleIndexType = (data) => {
  return index_type.value.find((item) => {
    return item.value === data;
  })?.label;
};

getList();
</script>

<style lang="scss" scoped>
.index-page {
  padding: 20px;
  :deep(.avatar-uploader .el-upload) {
    border: 1px dashed #cccccc;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }

  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 280px;
    height: 180px;
    text-align: center;
  }
}

:deep(.el-form-item[id="index"] .el-form-item__label) {
  // border:1px solid orange;
  width: 70px !important;
}
</style>
